import random

from OCC.Core.BRepPrimAPI import BRepPrimAPI_MakeBox
from OCC.Core.gp import gp_Pnt, gp_Ax2, gp_Dir, gp_XYZ
from OCC.Core.BRepBndLib import brepbndlib_AddOBB, brepbndlib_Add
from OCC.Core.Bnd import Bnd_OBB, Bnd_Box
from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_MakeVertex
from OCC.Core.BRepPrimAPI import BRepPrimAPI_MakeBox

from OCC.Display.SimpleGui import init_display

display, start_display, add_menu, add_function_to_menu = init_display()

def ConvertBndToShape(theBox):
  aBaryCenter = theBox.Center()
  aXDir = theBox.XDirection()
  aYDir = theBox.YDirection()
  aZDir = theBox.ZDirection()
  aHalfX = theBox.XHSize()
  aHalfY = theBox.YHSize()
  aHalfZ = theBox.ZHSize()

  ax = gp_XYZ(aXDir.X(), aXDir.Y(), aXDir.Z())
  ay = gp_XYZ(aYDir.X(), aYDir.Y(), aYDir.Z())
  az = gp_XYZ(aZDir.X(), aZDir.Y(), aZDir.Z())
  p = gp_Pnt(aBaryCenter.X(), aBaryCenter.Y(), aBaryCenter.Z())
  anAxes = gp_Ax2(p, gp_Dir(aZDir), gp_Dir(aXDir))
  anAxes.SetLocation(gp_Pnt(p.XYZ() - ax*aHalfX - ay*aHalfY - az*aHalfZ))
  aBox = BRepPrimAPI_MakeBox(anAxes, 2.0*aHalfX, 2.0*aHalfY, 2.0*aHalfZ).Shape()
  return aBox

# 创建OBB
obb = Bnd_OBB()

# 创建AABB
bbox = Bnd_Box() # 首先创建一个空的包围盒
tol= 1e-4
bbox.SetGap(tol)

n = 10
for _ in range(n):
    x = random.uniform(100, 500)
    y = random.uniform(100, 500)
    z = random.uniform(100, 500)
    p = BRepBuilderAPI_MakeVertex(gp_Pnt(x, y, z)).Shape()
    display.DisplayShape(p)
    brepbndlib_AddOBB(p, obb)
    brepbndlib_Add(p, bbox, True) # 将形状添加到包围盒中

obb_shape = ConvertBndToShape(obb)
display.DisplayShape(obb_shape, transparency=0.5)

XMin, YMin, ZMin, XMax, YMax, ZMax = bbox.Get() # 获取包围盒的信息

# 绘制包围盒
xmin = XMin
xmax = XMax
xlen = XMax - XMin
ymin = YMin
ymax = YMax
ylen = YMax - YMin
zmin = ZMin
zmax = ZMax
zlen = ZMax - ZMin

center = gp_Pnt((XMax + XMin) / 2,
                     (YMax + YMin) / 2,
                     (ZMax + ZMin) / 2)
box = BRepPrimAPI_MakeBox(gp_Pnt(xmin,ymin,zmin),gp_Pnt(xmax,ymax,zmax)).Shape()

display.DisplayShape(box, transparency=0.5)
start_display()
